package com.atlc.preview.project.utils;

import com.atlc.preview.project.model.Pages;
import com.atlc.preview.project.model.Problem;

import javax.swing.*;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 梁冲
 * @version 1.0
 * @email 1357042069@qq.com
 * @date 2021/11/25
 */
public class FileAnalyseUtils {

    private static final char[] FLAG = {'、', '（', '(', ')','）', '.', ' '};

    private static final String[] TYPES = {"单选题", "多选题", "判断题"};

    private static final String PROBLEM_TITLE = "problemTitle";

    private static final String PROBLEM_SEQUENCE = "problemSequence";

    private static final String CHOOSE = "choose";

    private static String curType = "";

    private static String title = "";

    private static Integer totalScore = 0;

    public static Pages analyseTestPaper(File file){
        String fileName = file.getName();
        int index = fileName.indexOf('.');
        if (!"txt".equals(fileName.substring(index+1))) {
            return null;
        }
        if (file.exists() && file.isFile()) {
           return loadFile(file);
        }
        return null;
    }

    private static String analyseStr(String str) {
        if ("".equals(str)) {
            return null;
        }
        if (str.indexOf(FLAG[0]) >= 0) {
            for (String s : TYPES) {
                if (str.contains(s)) {
                    return s;
                }
            }
            return PROBLEM_TITLE;
        }else if (str.indexOf(FLAG[5]) >= 0) {
            return CHOOSE;
        }else {
            return PROBLEM_SEQUENCE;
        }
    }
    private static String getAnswer(String str) {
        int i = str.indexOf(FLAG[1]);
        if (i == -1) {
            i = str.indexOf(FLAG[2]);
        }
        int indexOf = str.indexOf(FLAG[3]);
        if (indexOf == - 1) {
            indexOf = str.indexOf(FLAG[4]);
        }
        StringBuilder answer = new StringBuilder();
        while (i++ < indexOf) {
            boolean flag = str.charAt(i) == FLAG[6] || str.charAt(i) == FLAG[1] || str.charAt(i) == FLAG[2] || str.charAt(i) == FLAG[3] || str.charAt(i) == FLAG[4];
            if (flag) {
                continue;
            }
            answer.append(str.charAt(i));
        }
        return answer.toString();
    }
    public static Pages getPages(List<String> list) {
        List<String> titles = new ArrayList<>();
        List<String> answer = new ArrayList<>();
        Map<String, Integer> scoreMap = new HashMap<>();
        List<String> types = new ArrayList<>();
        List<String> choose = new ArrayList<>();
        List<List<String>> chooses = new ArrayList<>();
        boolean first = true;
        int count = 0;
        for (String str : list) {
            if (first) {
                title = str;
                first = false;
            }else {
                String result = analyseStr(str);
                if (result == null) {
                    break;
                }
                // 如果为选项
                if (result.equals(CHOOSE)) {
                    if (curType.equals(TYPES[0]) || curType.equals(TYPES[1])) {
                        if (count % 4 == 0 && count != 0) {
                            chooses.add(choose);
                            choose = new ArrayList<>();
                        }
                    }else {
                        if (count % 2 == 0 && count != 0) {
                            chooses.add(choose);
                            choose = new ArrayList<>();
                        }
                    }
                    choose.add(str);
                    count++;
                }else if (result.equals(PROBLEM_TITLE)) {
                    String analyseAnswer = getAnswer(str);
                    answer.add(analyseAnswer);
                    titles.add(str.replace(analyseAnswer, ""));
                }else if (result.equals(PROBLEM_SEQUENCE)){
                    int key = titles.size() - 1;
                    if (key != -1) {
                        String s = titles.get(key);
                        titles.set(key, s +"\n"+str);
                    }
                }else {
                    for (String t : TYPES) {
                        if (str.contains(t)) {
                            curType = t;
                            scoreMap.put(curType, getScore(str));
                            types.add(t);
                            break;
                        }
                    }
                }
            }
        }
        // 最后一次分开
        chooses.add(choose);
        List<Problem> problemList = initProblems(chooses, answer, scoreMap, titles);
        return initPages(types, problemList);
    }

    private static int getScore(String str) {
        int score = 0;
        for (int i = str.indexOf('每') + 2; i < str.indexOf('分'); i++) {
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                score = score * 10 + str.charAt(i) - '0';
            }
        }
        return score;
    }


    private static Pages loadFile(File file) {
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            inputStreamReader = new InputStreamReader(new FileInputStream(file), "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            List<String> list = bufferedReader.lines().collect(Collectors.toList());
            return getPages(list);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private static List<Problem> initProblems(List<List<String>> chooses, List<String> answer, Map<String, Integer> scoreMap, List<String> titles) {
        List<Problem> problemList = new ArrayList<>();
        for (int i = 0; i < titles.size(); i++) {
            String title = titles.get(i);
            List<String> choosesForEach = chooses.get(i);
            String answerForEach = answer.get(i);
            String typeForEach = judgeType(answerForEach);
            Integer score = scoreMap.get(typeForEach);
            totalScore += score;
            Problem problem = new Problem(title, typeForEach, score, choosesForEach, answerForEach);
            problemList.add(problem);
        }
        return problemList;
    }

    private static String judgeType(String answerForEach) {
        boolean isJudge = answerForEach.equals("正确") || answerForEach.equals("错误");
        return answerForEach.length() == 1 ? Const.SINGLE : isJudge ? Const.JUDGE : Const.MULTIPLE;
    }

    private static Pages initPages(List<String> types, List<Problem> problemList) {
        Pages pages = new Pages();
        pages.setTitle(title);
        pages.setTypes(types);
        pages.setProblemList(problemList);
        pages.setTotalScore(totalScore);
        return pages;
    }

    static class Const {
        public static final String SINGLE = "单选题";
        public static final String MULTIPLE = "多选题";
        public static final String JUDGE = "判断题";
    }
}

